<template>
  <div class="kpi">
    <van-sticky>
      <van-nav-bar title="选择事前申请单" left-text="返回" left-arrow @click-left="returnBtn">
        <template #right>
          <!-- <van-icon name="search" size="22" /> -->
          <!-- <van-button type="primary" size="mini"  class="btns-a" @click="onSureBtn">确认选择</van-button> -->
        </template>
      </van-nav-bar>
    </van-sticky>
    <div class="kpi-list-content">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          error-text="请求失败，点击重新加载"
          @load="getList"
          :offset='0'
        >
          <div class="list">
            <van-empty image="search" description="暂无数据" v-if="list.length === 0" />
            <ul v-else>
              <van-radio-group v-model="tableRadio" @change="handleCurrentChange">
                <li v-for="(item,index) in list" :key="item.id" @click="handleCurrentChange(item, index)" :class="{'active': oIndex === index}">
                  <div class="list-left">
                    <div class="list-text"><span>{{ item.reason }}</span></div>
                    <span class="list-amount">¥{{ item.amount }}</span>
                  </div>
                  <div class="list-m">
                    <DictTag :dict-list="getDictList('ExpenditureApplicationType')" :dict-key="item.applicationType" />
                    <LabelTag :foreignList="organizationList" :foreignIds="item.applicationOrganizationId" :foreignLabel="'organizationName'" />
                    <LabelTag :foreignList="userList" :foreignIds="item.applicationUserId" :foreignLabel="'name'" />
                  </div>
                  <div class="list-btn">
                    <EnumTag :enumList="getEnumList('ExpenditureKpiState')" :enumKey="item.state" />
                    <van-button type="default" plain size="mini" style="margin: 0 0.7rem" @click.self="kpiDetailsBtn(item)">查看详情</van-button>
                  </div>
                  <van-icon name="success" class="active-ico" v-if="oIndex === index" />
                </li>
                <!-- <li v-for="item in list" :key="item.id">
                  <div class="list-left">
                    <div class="list-text">单号：<span>{{ item.applicationCode }}</span></div>
                    <div class="list-text">金额：<span>￥{{ item.amount }}</span></div>
                    <div class="list-text">请款事项：<span>{{ item.items }}</span></div>
                  </div>
                  <div class="list-btn">
                    <van-button type="primary" size="mini" style="margin-right: 0.7rem" @click="kpiDetailsBtn(item)">详情</van-button>
                    <van-radio :name="item.id" icon-size="24px" />
                  </div>
                </li> -->
              </van-radio-group>
            </ul>
          </div>
        </van-list>
      </van-pull-refresh>
      <div class="btns">
        <van-button icon="certificate" type="primary" class="btns-a" round  @click="onSureBtn" color="#4fa2f7" :disabled=" !(typeof(oIndex) === 'number') ">确认选择</van-button>
      </div>
    </div>
    <van-popup v-model:show="isShowModel" :closeable="true" :style="{ height: '80%', width: '90%' }">
      <div class="model">
        <div class="model-head">事前申请单详情</div>
        <div class="model-content">
          <div class="content">
            <span>申请单号：</span>
            <span>{{ expenditureApplicationObj.applicationCode }}</span>
          </div>
          <div class="content">
            <span>申请日期：</span>
            <span>{{ expenditureApplicationObj.applicationDate?.substring(0, 10) }}</span>
          </div>
          <div class="content">
            <span>申请人部门：</span>
            <span>{{ showIdLabel(organizationList, expenditureApplicationObj.applicationOrganizationId, 'organizationName') }}</span>
          </div>
          <div class="content">
            <span>申请人用户：</span>
            <span>{{ showIdLabel(userList, expenditureApplicationObj.applicationUserId, 'name') }}</span>
          </div>
          <div class="content">
            <span>事前用款申请单类型：</span>
            <span>
              <DictTag :dict-list="getDictList('ExpenditureApplicationType')" :dict-key="expenditureApplicationObj.applicationType" />
            </span>
          </div>
          <div class="content">
            <span>申请金额：</span>
            <MoneyTag :money="expenditureApplicationObj.amount" />
          </div>
          <div class="content">
            <span>请款事由：</span>
            <span>{{ expenditureApplicationObj.items }}</span>
          </div>
          <div class="content">
            <span>支出事项：</span>
            <span>{{ expenditureApplicationObj.reason }}</span>
          </div>
          <div class="content">
            <span>备注：</span>
            <span>{{ expenditureApplicationObj.remark }}</span>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
  
</template>
<script setup>
import { ref, watch } from 'vue'
import {doGet} from "@/config/http";
import {
  svc,
  showDictKeyLabel,
  showEnumKeyLabel,
  getDictList,
  getEnumList,
  alertErrorMsg,
  showIdLabel, 
  getListPageSize
} from "@/config/common";
import useUserStore from "@/store/modules/user";
import {getUserId} from "@/config/cookie";
import initListStore from '@/store/modules/initList'

const props = defineProps({
  itemsVisible: {
    required: true,
    type: Boolean,
  },
  state: {
    required: false,
    type: String,
  },
  expenditureKpiId: {
    required: false,
    type: String,
  },
  kpiId: {
    required: false,
    type: String,
  },
})

let tableRadio = ref('')
let list = ref([])
let loading = ref(false)
let finished = ref(false)
let refreshing = ref(false)
let isShowModel = ref(false)
let expenditureApplicationObj = ref(null)

let listQuery = ref({
  expenditureKpiId: null, // 指标单表ID
  applicationCode: null, // 申请单号
  applicationDate: null, // 申请日期
  applicationType: null, // 用款申请单类型
  amount: null, // 申请金额
  items: null, // 请款事项
  reason: null, // 支出事由
  applicationOrganizationId: useUserStore().organization.organizationType !== '1' ? useUserStore().organization.id : '',
  applicationUserId: useUserStore().organization.organizationType !== '1' ? getUserId() : '',
  state: '2', // 状态
  remark: null, // 备注
  id: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  deleted: null,
  version: null,
  applicationDateRange: [],
  pageNum: 0,
  pageSize: 12
})
let radioRow = null

let governmentList = initListStore().governmentList
let organizationList = initListStore().organizationList
let userList = initListStore().userList
let expenditurePtypeList = initListStore().expenditurePtypeList
let expenditureFunctionalList = initListStore().expenditureFunctionalList
let expenditureFiscalList = initListStore().expenditureFiscalList
let oIndex = ref(null)


const emit = defineEmits(['close', 'expenditureKpiSelect'])

watch(() => [props.itemsVisible, props.expenditureKpiId], async vals => {
  console.log('11111222333')
  if (vals[0] === true) {
    await getList()
    if (vals[1]) {
      console.log('vals[1]',vals[1])
      
      // tableRadio.value = vals[1]
    }
  }
})

// async function initList() {
//   let p1 = doGet(svc, '/government/page', {pageSize: getListPageSize()}, false)
//   let p2 = doGet(svc, '/organization/page', {pageSize: getListPageSize()}, false)
//   let p3 = doGet(svc, '/user/page', {pageSize: getListPageSize()}, false)
//   let p4 = doGet(svc, '/expenditure-ptype/page', {pageSize: getListPageSize()}, false)
//   let p5 = doGet(svc, '/expenditure-functional/page', {pageSize: getListPageSize()}, false)
//   let p6 = doGet(svc, '/expenditure-fiscal/page', {pageSize: getListPageSize()}, false)
//   let resArray = await Promise.all([p1, p2, p3, p4, p5, p6])
//   governmentList.value = resArray[0]['records']
//   organizationList.value = resArray[1]['records']
//   userList.value = resArray[2]['records']
//   expenditurePtypeList.value = resArray[3]['records']
//   expenditureFunctionalList.value = resArray[4]['records']
//   expenditureFiscalList = resArray[5]['records']
// }

// 获取数据
async function getList() {
  // await initList()
  listQuery.value.pageNum++
  console.log('props.expenditureKpiId',props.expenditureKpiId)
  listQuery.value.expenditureKpiId = props.expenditureKpiId ? props.expenditureKpiId : null
  let res = await doGet(svc, '/expenditure-application/page', listQuery.value)

  if (refreshing.value) {
    list.value = [];
    refreshing.value = false;
  }

  if(list.value.length === 0) {
    list.value = res['records']
  } else {
    list.value = list.value.concat(res['records'])
  }
  
  loading.value = false
  
  if (list.value.length >= parseInt(res['total'])) {
    finished.value = true
    listQuery.value.pageNum = 0
  } else {
    finished.value = false
  }
  
}

// 选择
// 选择
const handleCurrentChange = (val, index) =>{
  console.log('val=>',val);
  oIndex.value = index
  radioRow = val
}

const kpiDetailsBtn = (item) =>{
  expenditureApplicationObj.value = item
  isShowModel.value = true
}

// 点确定
function onSureBtn() {
  if (!radioRow) {
    alertErrorMsg('请选择指标单')
    return
  }
  emit('expenditureKpiSelect', radioRow)
  emit('close')
}

function returnBtn() {
  emit('close')
}

const onRefresh = () => {
  // // 清空列表数据
  finished.value = false;
  listQuery.value.pageNum = 0
  list.value = []
  // 重新加载数据
  // 将 loading 设置为 true，表示处于加载状态
  loading.value = true;
  getList();
};

</script>
<style>
.list-m .el-tag {
  color: #000 !important;
}
</style>
<style scoped lang="scss">
.kpi {
    width: 100%;
    height: 100vh;
    background-color: #f5f2f2;
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    overflow-y: auto;
}

.kpi-list-content {
  width: 100%;
  height: 100%;
}
.list-text {
  width: 70%;
  overflow: hidden; /* 确保超出容器的内容被裁剪 */
  white-space: nowrap; /* 确保文本在一行内显示 */
  text-overflow: ellipsis; /* 超出部分显示省略号 */
  // color: #1db0bf;
}
.list {
  width: 100%;
  height: calc( 100vh - 8rem);
  & ul {
    width: 100%;
    height: 100%;
    padding: 0 .625rem;
    scroll-behavior: smooth;
    overflow-y: auto;
    & li {
      border-bottom: 1px solid #C3C3C3;
      border-radius: 6px;
      margin: .625rem 0;
      background: #fff;
      padding: .625rem;
      box-shadow:0 0 5px var(--van-gray-5);
      position: relative;
      .list-left {
        display: flex;
        justify-content: space-between;
        // margin-top: .625rem;
       
      }
      .list-m {
        display: flex;
        align-items: center;
        // justify-content: space-between;
        flex-wrap: wrap;
        margin-top: .625rem;
        & span {
          color: 000;
          font-size: .875rem;
          border: 1px solid #000;
          padding: 0.1rem .5rem;
          display: inline-block;
          margin: 0 .3125rem;
          border-radius: 2px;
        }
      }
      .list-btn {
        display: flex;
        justify-content: flex-end;
        margin-top: .625rem;
      }
      & span {
        // color: #95d475;
        font-size: .875rem;
        font-weight: bold;
        // color: #000;
      }
    }
    & li.active {
      background: #fff1f1;
      box-shadow:0 0 5px #9b0f65;
    }
    .active-ico {
      position: absolute;
      left: 0;
      bottom: 0;
      background: #dfc059;
      color: #fff;
      border-radius: 50%;
    }
  }
}
.btns {
  width: 100%;
  // padding: 0 .625rem;
  overflow: hidden;
  position: fixed;
  bottom: 0.2rem;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}
.list-amount {
  padding: .3rem 0.8rem;
  border-radius: 30px;
  color: #fff;
  background: #dfc059;
  
}
.model-head {
  font-size: 1.5rem;
  font-weight: bold;
  margin-top: 2rem;
  text-align: center;
}
.model-content {
  padding: 0 1.2rem;
}
.content {
  padding: .625rem 0;
  color: var(--van-gray-10);
  display: flex;
  // align-items: center;
}
.content span:nth-child(1) {
  display: inline-block;
  text-align: top;
  // width: 46%;
  min-width: 25%;
}
</style>